<?php

namespace app\admin\controller;

use app\common\model\Domains;
use app\common\model\Dsps;
use think\Request;

class Dsp extends Base
{

    public function index(Request $request)
    {
        if ( $post = $request->isAjax() ){

            $page = input('param.page/d', 1);
            $limit = input('param.limit/d', 20);

            $arrs = Dsps::order(['id'=>'desc'])->page($page)->limit($limit)->select();

            if ( count($arrs) > 0 ){
                foreach ( $arrs as $k=>$v){
                    $v['domain'] = Domains::getOneData(2);
                }
            }

            $data = array(
                'data'      => $arrs,
                'count'     => Dsps::count('id'),
                'code'      => 0,
                'msg'       => '',
            );
            return json($data);
        }

        return view();
    }



    // 添加、保存数据
    public function create(Request $request)
    {

        if ( $request->isPost() ){
            $post = trimAll($request->post());
            $post['alias'] = getRandStr(8);

            // 把换行，替换成||
            $post['share_end_img'] = huanhangToStr($post['share_end_img']);

            if ( !isset($post['status']) ){
                $post['status'] = 2;
            }

            unset($post['touxiang'], $post['file']);

            //写入数据库
            if ( Dsps::create($post) ){
                createLog('添加 短视频 成功：' . $post['title']);
                success('操作成功');
            }else{
                createLog('添加 短视频 失败：' . $post['title']);
                error('操作失败');
            }

        }

        return view();
    }


    // 编辑、保存数据
    public function edit(Request $request, $id)
    {

        if ( $request->isPost() ){
            $post = trimAll($request->post());

            // 把换行，替换成||
            $post['share_end_img'] = huanhangToStr($post['share_end_img']);

            if ( !isset($post['status']) ){
                $post['status'] = 2;
            }

            unset($post['touxiang'], $post['file']);

            //写入数据库
            if ( Dsps::where('id', $id)->update($post) ){
                createLog('编辑 短视频 成功：' . $post['title']);
                success('操作成功');
            }else{
                createLog('编辑 短视频 失败：' . $post['title']);
                error('操作失败');
            }

        }

        //加载数据
        $data = Dsps::get($id);

        // 把||，替换成换行
        $data['share_end_img'] = str_replace('||', PHP_EOL, $data['share_end_img']);

        $this->assign('data', $data);
        return view();
    }


}
